package sort;

import java.util.Arrays;
import java.util.Random;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * User:Mr.Du
 * Date:2022/3/8
 * Time:16:52
 */
public class 插入排序 {

    public static void main(String[] args) {

        int[] arr = new int[10];
        Random r = new Random();

        for(int j = 0;j<10;j++){
            for(int i = 0;i<arr.length;i++){
                arr[i] = r.nextInt(50);
            }
            System.out.println("原数组: ");
            System.out.println(Arrays.toString(arr));
            insertSort(arr);
            System.out.println("插入排序后的数组: ");
            System.out.println(Arrays.toString(arr));
        }

    }

    private static void insertSort(int[] arr) {
        int j = 0;
        for(int i = 1;i<arr.length;i++) {
            if(arr[i]<arr[i-1]) {
                int t = arr[i];  //记录当前位置元素
                for(j = i - 1;j>=0&&t<arr[j];j--) {
                    arr[j+1] = arr[j];
                }
                arr[j+1] = t;
            }
        }
    }
}
